<template>
  <div>
    <!-- 页面标题 -->
    <v-row class="mb-6">
      <v-col cols="12" md="6" class="d-flex justify-end align-center">
        <v-chip :color="statusColor" variant="elevated" class="me-3">
          {{ formattedDate }}
        </v-chip>
        <v-btn
          color="primary"
          prepend-icon="mdi-qrcode-scan"
          @click="openQRScanner"
        >
          扫描二维码
        </v-btn>
      </v-col>
    </v-row>



  

    <!-- 学生列表 -->
    <v-card>
      <v-card-title>
        <v-spacer></v-spacer>
        <v-text-field
          v-model="searchText"
          append-inner-icon="mdi-magnify"
          label="搜索学生"
          variant="filled"
          single-line
          hide-details
          density="compact"
          style="max-width: 300px;"
        ></v-text-field>
      </v-card-title>
      
      <v-card-text>
        <v-row>
          <v-col
            v-for="student in filteredStudents"
            :key="student.id"
            cols="12"
            sm="6"
            md="4"
            lg="3"
          >
            <StudentCard
              :student="student"
              :show-parent-info="true"
              :is-arrival-page="true"
              @request-leave="handleRequestLeave"
              @edit-notes="handleEditNotes"
            />
          </v-col>
        </v-row>
        
        <div v-if="studentsStore.loading" class="text-center py-8">
          <v-progress-circular indeterminate color="primary"></v-progress-circular>
          <p class="mt-4">加载中...</p>
        </div>
        
        <div v-if="!studentsStore.loading && filteredStudents.length === 0" class="text-center py-8">
          <v-icon size="64" color="grey">mdi-account-group-outline</v-icon>
          <p class="text-h6 mt-4">暂无学生数据</p>
        </div>
        
        <!-- 分页组件 -->
        <div v-if="!studentsStore.loading && totalItems > itemsPerPage" class="d-flex justify-center mt-6">
          <v-pagination
            v-model="currentPage"
            :length="Math.ceil(totalItems / itemsPerPage)"
            :total-visible="7"
            color="primary"
          ></v-pagination>
        </div>
      </v-card-text>
    </v-card>

    <!-- 二维码扫描对话框 -->
    <v-dialog v-model="qrDialog" max-width="500">
      <v-card>
        <v-card-title>
          <v-icon class="me-2">mdi-qrcode-scan</v-icon>
          扫描学生二维码
        </v-card-title>
        
        <v-card-text>
          <div id="qr-reader" style="width: 100%;"></div>
          
          <v-divider class="my-4"></v-divider>
          
          <v-text-field
            v-model="manualCode"
            label="或手动输入学号/二维码"
            variant="filled"
            density="comfortable"
            append-inner-icon="mdi-magnify"
            @click:append-inner="searchByCode"
            @keyup.enter="searchByCode"
          ></v-text-field>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="closeQRScanner">关闭</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 请假确认对话框 -->
    <v-dialog v-model="leaveDialog" max-width="400">
      <v-card>
        <v-card-title>
          <v-icon class="me-2" color="orange">mdi-calendar-remove</v-icon>
          标记请假
        </v-card-title>
        
        <v-card-text>
          <div class="text-center mb-4">
            <v-avatar size="64" color="primary">
              <span class="text-h5 text-white">{{ selectedStudent?.name?.charAt(0) }}</span>
            </v-avatar>
            <h3 class="mt-2">{{ selectedStudent?.name }}</h3>
            <p class="text-caption">{{ selectedStudent?.student_no }}</p>
          </div>
          
          <v-alert type="info" variant="tonal" class="mb-4">
            将该学生标记为请假状态
          </v-alert>
          
          <v-textarea
            v-model="leaveNotes"
            label="请假原因（可选）"
            variant="filled"
            rows="3"
            density="comfortable"
            placeholder="请输入请假原因..."
          ></v-textarea>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="leaveDialog = false">取消</v-btn>
          <v-btn color="orange" @click="confirmLeave" :loading="updating">确认请假</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    
    <!-- 独立备注编辑对话框 -->
    <v-dialog v-model="notesDialog" max-width="400">
      <v-card>
        <v-card-title>
          <v-icon class="me-2">mdi-note-edit</v-icon>
          编辑学生备注
        </v-card-title>
        
        <v-card-text>
          <div class="text-center mb-4">
            <v-avatar size="64" color="primary">
              <span class="text-h5 text-white">{{ selectedStudent?.name?.charAt(0) }}</span>
            </v-avatar>
            <h3 class="mt-2">{{ selectedStudent?.name }}</h3>
            <p class="text-caption">{{ selectedStudent?.student_no }}</p>
          </div>
          
          <v-alert type="info" variant="tonal" class="mb-4">
            备注可以在任何时候添加或修改，不与考勤状态绑定
          </v-alert>
          
          <v-textarea
            v-model="editingNotes"
            label="备注内容"
            variant="filled"
            rows="4"
            density="comfortable"
            placeholder="请输入备注信息..."
            counter
            maxlength="500"
          ></v-textarea>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="notesDialog = false">取消</v-btn>
          <v-btn color="primary" @click="confirmNotesUpdate" :loading="updating">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useStudentsStore } from '@/stores/students'
import { useSocketStore } from '@/stores/socket'
import StudentCard from '@/components/StudentCard.vue'

const authStore = useAuthStore()
const studentsStore = useStudentsStore()
const socketStore = useSocketStore()

// 响应式数据
const updating = ref(false)
const searchText = ref('')
const qrDialog = ref(false)
const leaveDialog = ref(false)
const notesDialog = ref(false)
const manualCode = ref('')
const selectedStudent = ref(null)
const leaveNotes = ref('')
const editingNotes = ref('')
const qrScanner = ref(null)

// 分页相关数据
const currentPage = ref(1)
const itemsPerPage = ref(10) // 每页显示10个学生卡片
const totalItems = ref(0) // 总学生数量

// 计算属性
const formattedDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

const statusColor = computed(() => {
  const hour = new Date().getHours()
  if (hour < 9) return 'green'
  if (hour < 12) return 'orange'
  return 'red'
})



const filteredStudents = computed(() => {
  // 后端已处理分页和搜索，直接返回学生数据
  return studentsStore.students
})

const totalStudents = computed(() => studentsStore.students.length)
const presentCount = computed(() => studentsStore.students.filter(s => s.arrival_status === 'present').length)
const leaveCount = computed(() => studentsStore.students.filter(s => s.arrival_status === 'leave').length)
const abnormalCount = computed(() => studentsStore.students.filter(s => s.arrival_status === 'abnormal').length)

// 方法
const loadStudents = async () => {
  try {
    // 确保用户信息已加载，包含班级信息
    if (!authStore.user?.classes || authStore.user.classes.length === 0) {
      await authStore.fetchProfile()
    }
    
    // 检查教师是否有分配的班级
    if (!authStore.user?.classes || authStore.user.classes.length === 0) {
      console.error('教师未分配班级')
      return
    }
    
    // 获取教师的第一个班级ID（通常教师只负责一个班级）
    const classId = authStore.user.classes[0].id
    
    // 使用WebSocket获取班级考勤信息
    socketStore.socket.emit('get-class-attendance', {
      teacherId: authStore.user.id, // 修正为user.id
      userRole: authStore.userRole,
      classId: classId, // 添加班级ID参数
      date: new Date().toISOString().split('T')[0],
      page: currentPage.value,
      limit: itemsPerPage.value,
      search: searchText.value || undefined
    })
  } catch (error) {
    console.error('加载学生列表失败:', error)
    window.showNotification?.('加载学生列表失败', 'error')
  }
}

const openQRScanner = () => {
  qrDialog.value = true
  // 延迟初始化扫描器以确保DOM已渲染
  setTimeout(initQRScanner, 100)
}

const closeQRScanner = () => {
  if (qrScanner.value) {
    qrScanner.value.clear()
    qrScanner.value = null
  }
  qrDialog.value = false
  manualCode.value = ''
}

const initQRScanner = async () => {
  try {
    const { Html5QrcodeScanner } = await import('html5-qrcode')
    
    qrScanner.value = new Html5QrcodeScanner(
      'qr-reader',
      {
        qrbox: { width: 250, height: 250 },
        fps: 20
      },
      false
    )
    
    qrScanner.value.render(onScanSuccess, onScanFailure)
  } catch (error) {
    console.error('初始化二维码扫描器失败:', error)
    window.showNotification?.('二维码扫描器初始化失败', 'error')
  }
}

const onScanSuccess = (decodedText) => {
  searchByCode(decodedText)
  closeQRScanner()
}

const onScanFailure = (error) => {
  // 忽略扫描失败（通常是没有检测到二维码）
}

const searchByCode = async (code = manualCode.value) => {
  if (!code) return
  
  try {
    // 使用WebSocket处理二维码扫描入园
    socketStore.socket.emit('qr-scan-arrival', {
      qrCode: code,
      teacherId: authStore.user.id, // 修正为user.id
      userRole: authStore.userRole
    })
    
    if (qrDialog.value) {
      closeQRScanner()
    }
    
  } catch (error) {
    console.error('扫码入园失败:', error)
    window.showNotification?.('扫码入园失败', 'error')
  }
}

// 处理请假请求
const handleRequestLeave = (student) => {
  if (student.arrival_status === 'present') {
    window.showNotification?.('学生已入园，无法标记请假', 'warning')
    return
  }
  
  selectedStudent.value = student
  leaveNotes.value = ''
  leaveDialog.value = true
}

// 处理备注编辑
const handleEditNotes = (student) => {
  selectedStudent.value = student
  editingNotes.value = student.notes || ''
  notesDialog.value = true
}

// 确认请假
const confirmLeave = async () => {
  if (!selectedStudent.value) return
  
  try {
    updating.value = true
    
    // 使用WebSocket更新学生状态为请假
    socketStore.socket.emit('update-student-arrival', {
      studentId: selectedStudent.value.id,
      status: 'leave',
      notes: leaveNotes.value,
      teacherId: authStore.user.id,
      userRole: authStore.userRole
    })
    
    leaveDialog.value = false
    window.showNotification?.(`${selectedStudent.value.name} 已标记为请假`, 'success')
    
  } catch (error) {
    console.error('标记请假失败:', error)
    window.showNotification?.('标记请假失败', 'error')
  } finally {
    updating.value = false
  }
}

// 二维码扫描后直接标记为已到
const markStudentPresent = async (student) => {
  try {
    updating.value = true
    
    await studentsStore.markStudentArrival({
      student_id: student.id,
      status: 'present'
    })
    
    // 更新本地数据
    studentsStore.updateStudentAttendance(student.id, {
      arrival_status: 'present',
      arrival_time: new Date().toTimeString().split(' ')[0]
    })
    
    window.showNotification?.(`${student.name} 入园成功`, 'success')
    
  } catch (error) {
    console.error('标记入园失败:', error)
    window.showNotification?.('标记入园失败', 'error')
  } finally {
    updating.value = false
  }
}

const handleQuickUpdate = async (data) => {
  const { student, status } = data
  
  try {
    updating.value = true
    
    // 使用WebSocket更新学生入园状态
    socketStore.socket.emit('update-student-arrival', {
      studentId: student.id,
      status: status,
      teacherId: authStore.user.id, // 修正为user.id
      userRole: authStore.userRole
    })
    
  } catch (error) {
    console.error('快速更新入园状态失败:', error)
    window.showNotification?.('快速更新失败', 'error')
    updating.value = false
  }
}

// 确认备注更新
const confirmNotesUpdate = async () => {
  if (!selectedStudent.value) return
  
  try {
    updating.value = true
    
    // 使用WebSocket更新学生备注
    socketStore.socket.emit('update-student-notes', {
      studentId: selectedStudent.value.id,
      notes: editingNotes.value,
      teacherId: authStore.user.id,
      userRole: authStore.userRole
    })
    
    notesDialog.value = false
    window.showNotification?.(`${selectedStudent.value.name} 备注已更新`, 'success')
    
  } catch (error) {
    console.error('更新备注失败:', error)
    window.showNotification?.('更新备注失败', 'error')
  } finally {
    updating.value = false
  }
}

// 监听器
watch(currentPage, () => {
  loadStudents()
})

// 防抖搜索
let searchTimeout = null
watch(searchText, () => {
  if (searchTimeout) clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    currentPage.value = 1 // 搜索时重置到第一页
    loadStudents()
  }, 500)
})

// WebSocket事件监听器
const setupSocketListeners = () => {
  if (!socketStore.socket) return
  
  // 监听班级考勤数据响应
  socketStore.socket.on('class-attendance-data', (response) => {
    if (response.success) {
      studentsStore.students = response.data.students || []
      totalItems.value = response.data.total || 0
    } else {
      console.error('获取班级考勤数据失败:', response.message)
      window.showNotification?.(response.message || '获取班级考勤数据失败', 'error')
    }
  })
  
  // 监听二维码扫描入园响应
  socketStore.socket.on('qr-scan-arrival-result', (response) => {
    if (response.success) {
      const student = response.data.student
      window.showNotification?.(`${student.name} 入园成功`, 'success')
      // 刷新学生列表
      loadStudents()
    } else {
      window.showNotification?.(response.message || '该学生不在您的班级中或扫码入园失败', 'error')
    }
  })
  
  // 监听学生入园状态更新响应
  socketStore.socket.on('student-arrival-updated', (response) => {
    updating.value = false
    if (response.success) {
      window.showNotification?.('入园状态更新成功', 'success')
      // 刷新学生列表
      loadStudents()
    } else {
      window.showNotification?.(response.message || '更新入园状态失败', 'error')
    }
  })
  
  // 监听学生状态实时更新
  socketStore.socket.on('student-status-updated', (data) => {
    // 实时更新学生列表
    loadStudents()
  })
}

// 清理WebSocket监听器
const cleanupSocketListeners = () => {
  if (!socketStore.socket) return
  
  socketStore.socket.off('class-attendance-data')
  socketStore.socket.off('qr-scan-arrival-result')
  socketStore.socket.off('student-arrival-updated')
  socketStore.socket.off('student-status-updated')
}

// 生命周期
onMounted(() => {
  setupSocketListeners()
  // 直接加载教师班级的学生
  loadStudents()
})

onUnmounted(() => {
  if (qrScanner.value) {
    qrScanner.value.stop()
  }
  cleanupSocketListeners()
})
</script>

<style scoped>
.student-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.status-chip {
  font-weight: 600;
}

/* 二维码扫描器样式 */
:deep(#qr-reader) {
  border: 2px dashed #ddd;
  border-radius: 8px;
}

:deep(#qr-reader__camera_selection) {
  margin-bottom: 16px;
}

:deep(#qr-reader__scan_region) {
  border-radius: 8px;
}

/* 颜色样本样式 */
.color-sample {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  flex-shrink: 0;
}

.color-sample.status-present {
  background: linear-gradient(135deg, #4CAF50, #66BB6A);
}

.color-sample.status-leave {
  background: linear-gradient(135deg, #FF9800, #FFB74D);
}

.color-sample.status-abnormal {
  background: linear-gradient(135deg, #F44336, #EF5350);
}

.color-sample.status-absent {
  background: linear-gradient(135deg, #9E9E9E, #BDBDBD);
}

.color-sample.status-bus {
  background: linear-gradient(135deg, #2196F3, #42A5F5);
}
</style>
